/*** Class Name: ifulfillRestAPIController
* Author: Accenture       Date: 7-Feb-2012
* Requirement/Project Name: iFULFILL
* Requirement/Project Description:SFDC should verify that the CSS system is not down prior to sending an outbound message.
* If the system is down then display an error message to the user (error message will be provided by SIL).
*
* **/

public with sharing class ifulfillRestAPIController{
 
 public Fullfilment_Item__c FI {get;set;}
 public string statusCode{get;set;}
 public string errorMessage{get;set;}
 public string stackTrace{get;set;}
 public String responseData ; 
 public Boolean sucessFlag{get;set;}
 public Boolean timeOutFlag{get;set;}
 public Boolean errorFlag{get;set;}
 public Boolean badRequestFlag{get;set;}
 public Boolean okFlag{get;set;} 
 public Boolean msgFlag{get;set;} 

 public Id Fufl;
 public String controlKey;

 public ifulfillRestAPIController(ApexPages.StandardController controller) {    
     FI = (Fullfilment_Item__c)controller.getRecord(); 
     msgFlag = true; 
     timeOutFlag =false;
     errorFlag =false; 
     badRequestFlag=false;
     sucessFlag =false;       
 } 
 /*
  *In this method we will check the CSS is up (or) down . 
  *if CSS is up Status changed to Complete ,PR Delivery Status chagnge to success.
  *if CSS is down we are displaying error message and PR Delivery Stats set to 'Failed'.
   */
   public pagereference dummy(){
       return null;
   }
   
  public pagereference getResponse() {        
        String endPoint;  
        string productIssue='';
        string rootProcessId='';
        string featureId='';  
        String lastModifiedDate= FI.LastModifiedDate.format('MM/dd/yyyy');
        System.debug('lastModifiedDate--->'+lastModifiedDate);
        AppEndPoints__c appEndPoints = AppEndPoints__c.getInstance();
        if(FI.Product_Issue__c !=null)
           productIssue=FI.Product_Issue__c;
           
        if(FI.RootProcessId__c !=null)
           rootProcessId=FI.RootProcessId__c + '';
           
        if(FI.Feature_Id__c !=null)
           featureId= FI.Feature_Id__c + '';
                    
        
        endPoint=appEndPoints.workflowCompleteURL__c+'/UpdateFulfillmentStatus?CustomerId='+FI.Customer_ID__c+'&RegionCode='+FI.FI_Region_Code__c+'&FeatureId='+featureId+'&Id='+FI.ID+'&ItemId='+FI.Item_Id__c+'&LastModifiedDate='+lastModifiedDate+'&OwnerId='+FI.OwnerId+'&PricePlanId='+FI.Price_Plan_Id_text__c+'&ProductCode='+FI.Product_Code__c+'&ProductIssue='+productIssue+'&RootProcessId='+rootProcessId;        
        HttpRequest req= new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint(endpoint);
        req.setTimeout(20000);  
        req.setHeader('Content-Length','1024');          
        req.setBody('CustomerId='+FI.Customer_ID__c+'&RegionCode='+FI.FI_Region_Code__c+'&FeatureId='+featureId+'&Id='+FI.ID+'&ItemId='+FI.Item_Id__c+'&LastModifiedDate='+lastModifiedDate+'&OwnerId='+FI.OwnerId+'&PricePlanId='+FI.Price_Plan_Id_text__c+'&ProductCode='+FI.Product_Code__c+'&ProductIssue='+productIssue+'&RootProcessId='+rootProcessId);
        System.debug('Req message -->'+req.getBody());
        
      try{  
       Http http = new Http();
       HttpResponse res= http.send(req);
       if(res.getStatusCode() == 200){
       
        msgFlag=false;
        String responseXML = res.getBody();
        System.debug('response-->'+res.toString());
        System.debug('responseXML ---->'+responseXML);        
        Dom.Document domDoc = new Dom.Document();          
        domDoc.load(responseXML);                
        Dom.XMLNode address = domDoc.getRootElement();   
        if(address.getChildElement('ErrorMessage', 'http://sil.service')!=null){     
            errorMessage= address.getChildElement('ErrorMessage', 'http://sil.service').getText();
        }
        if(address.getChildElement('StatusCode', 'http://sil.service')!=null){     
           statusCode = address.getChildElement('StatusCode', 'http://sil.service').getText();
        } 
        if(address.getChildElement('StackTrace', 'http://sil.service')!=null){     
           stackTrace= address.getChildElement('StackTrace', 'http://sil.service').getText();     
        }                         
        System.debug('errorMessage -->'+errorMessage);
        System.debug('statusCode -->'+statusCode);
        System.debug('stackTrace -->'+stackTrace);
        System.debug('response statuscode'+res.toString());
        if(statusCode !=null && integer.valueof(statusCode)== 0){
            system.debug('sucess');
            sucessFlag =true;
            timeOutFlag =false;
            errorFlag =false;
            badRequestFlag=false;
            
            ifulfillProductionReady.updateSetProductionReady(FI.Id);
            FI.status__c =IfullfillTextConstant.FI_WORKFLOW_COMPLETE_STATUS;
            FI.Production_staus__c=IfullfillTextConstant.FI_PRODUCTION_STATUS;
            FI.PR_Delivery_Status__c=IfullfillTextConstant.FI_PR_DELIVERY_SUCCESS_STATUS;
            FI.Status_Code__c=statusCode;
            system.debug('status__c ---->'+FI.status__c+'FI Production_staus__c'+FI.Production_staus__c);
            update FI;
        }else{
           System.debug('error Flag'+errorFlag);
          
           errorFlag =true;
           okFlag =true;
           timeOutFlag =false;
           sucessFlag =false;
           badRequestFlag=false;
           System.debug('after error Flag'+errorFlag+'okFlag' +okFlag);

           FI.PR_Delivery_Status__c=IfullfillTextConstant.FI_PR_DELIVERY_FAILED_STATUS;
           FI.Status_Code__c=statusCode;
           update FI;
        }
       }else if(res.getStatusCode() == 404){
           System.debug('Not Found'); 
           badRequestFlag=true;
           timeOutFlag =false;
           sucessFlag =false;
           errorFlag =false;  
           msgFlag=false;                 
           okFlag =true;
           FI.PR_Delivery_Status__c=IfullfillTextConstant.FI_PR_DELIVERY_FAILED_STATUS;
           FI.Status_Code__c='1';
           update FI;            
       } 
       }catch(CalloutException e){
           system.debug('exception is'+e+'exption contains--->'+e.getMessage());
             msgFlag=false;

           system.debug('exception is'+e+'exption contains--->'+e.getMessage().contains('Read timed out'));
           if(e.getMessage().contains('Read timed out')){
               badRequestFlag=false;
               timeOutFlag =true;
               sucessFlag =false;
               errorFlag =false;
               okFlag =true;
               FI.PR_Delivery_Status__c=IfullfillTextConstant.FI_PR_DELIVERY_FAILED_STATUS;
               FI.Status_Code__c='1';
               update FI;
           }else{
                badRequestFlag=true;
                okFlag=true;
                FI.PR_Delivery_Status__c=IfullfillTextConstant.FI_PR_DELIVERY_FAILED_STATUS;
                FI.Status_Code__c='1';
                update FI;
           }
           
       }
      return null;
   }   
}